from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import GoodsCategory, SKU
from goods.serializers import SKUSSerialziers, SKUSearchSeializer, SKUHistorySerialzier
from goods.utils import PageNum
from drf_haystack.viewsets import HaystackViewSet


class CategoriesView(APIView):
    def get(self, request, pk):
        cat3 = GoodsCategory.objects.get(id=pk)
        cat2 = cat3.parent
        cat1 = cat2.parent

        return Response({
            'cat1': cat1.name,
            'cat2': cat2.name,
            'cat3': cat3.name,
        })


class SKUSView(ListAPIView):
    serializer_class = SKUSSerialziers
    # queryset = SKU.objects.filter(category=)
    # 分页查询
    pagination_class = PageNum
    # 过滤
    filter_backends = [OrderingFilter]
    # 排序
    ordering_fields = ('create_time', 'sales', 'price')

    def get_queryset(self):
        pk = self.kwargs['pk']
        return SKU.objects.filter(category=pk)


class SKUSearchView(HaystackViewSet):
    index_models = [SKU]
    serializer_class = SKUSearchSeializer

    # 分页处理
    pagination_class = PageNum

# 用户浏览历史记录
class SKUHistoryView(CreateAPIView, ListAPIView):

    # serializer_class = SKUHistorySerialzier

    # queryset = SKU.objects.filter()
    def get_queryset(self):
        # 获取当前用户
        user = self.request.user
        # 建立链接
        conn = get_redis_connection('history')
        # 查询缓存数据 获取sku_id
        sku_ids = conn.lrange('history_%s'%user.id,0,100)
        # 根据sku_id 查询商品对象
        skus = SKU.objects.filter(id__in=sku_ids)
        return skus
    def get_serializer_class(self):
        if self.request.method == "POST":
            return SKUHistorySerialzier
        else:
            return SKUSSerialziers
